/*
 * @Author: MuQuanyu(MQy)
 * @Date: 2025-08-30 09:44:57
 * @LastEditTime: 2025-10-11 09:19:54
 * @email: muquanyu@outlook.com
 */
// 建议用vue3响应式写法去写 pinia
import { defineStore } from "pinia";
import { ref } from "vue";
import tool from "@/utils/common/index";
import type { TokenTimes } from "@/utils/http/types";
import type { RouteRecordRaw } from "vue-router";
import { useSysStore } from "./sys";
import type { UserInfoVO } from "@/api/sys/user/types";

export const useAuthStore = defineStore("authStore", () => {
  const userInfo = ref<UserInfoVO | null>(null);
  const isLogin = ref(false);
  const accessToken = ref<string | null>(tool.getLocalStore("accessToken") ?? null);
  const refreshToken = ref<string | null>(tool.getLocalStore("accessToken") ?? null);
  const tokenTimes = ref<TokenTimes | null>();
  const dynamicRoutes = ref<RouteRecordRaw[]>(tool.getLocalStore("yu-dynamicRoutes") ?? []);
  const keepAliveList = ref<string[]>(tool.getLocalStore("yu-keepAliveList") ?? []);
  const topLabelList = ref<TopLabel[]>(tool.getLocalStore("yu-topLabelList") ?? []);
  const setAccessToken = (val: string | null) => {
    accessToken.value = val;
    tool.setLocalStore("accessToken", accessToken.value); // 存储 accessToken 到本地
  };
  const setRefreshToken = (val: string | null) => {
    refreshToken.value = val;
    // 刷新Token的前置令牌
    tool.setLocalStore("refreshToken", refreshToken.value); // 存储 refreshToken 到本地
  };
  const setTokenTimes = (val: TokenTimes | null) => {
    tokenTimes.value = val;
    // 如果后端提供的话，可以存下
    tool.setLocalStore("tokenTimes", tokenTimes.value);
  };
  const clearToken = () => {
    accessToken.value = null;
    refreshToken.value = null;
    tool.removeLocalStore("accessToken");
    tool.removeLocalStore("refreshToken");
  };
  const setDynamicRoutes = (val: RouteRecordRaw[]) => {
    dynamicRoutes.value = val;
    tool.setLocalStore("yu-dynamicRoutes", val);
  };
  const setKeepAliveList = (val: string[]) => {
    keepAliveList.value = val;
    tool.setLocalStore("yu-keepAliveList", val);
  };
  const setTopLabelList = (val: TopLabel[]) => {
    const sysStore = useSysStore();
    topLabelList.value = val;
    if (sysStore.isPersistenceTopLabelBar) {
      tool.setLocalStore("yu-topLabelList", val);
    }
  };
  const setUserInfo = (val: UserInfoVO | null) => {
    userInfo.value = val;
  };
  const setIsLogin = (val: boolean) => {
    isLogin.value = val;
  };

  return {
    accessToken,
    refreshToken,
    tokenTimes,
    dynamicRoutes,
    keepAliveList,
    topLabelList,
    userInfo,
    isLogin,
    setAccessToken,
    setRefreshToken,
    clearToken,
    setTokenTimes,
    setDynamicRoutes,
    setKeepAliveList,
    setTopLabelList,
    setUserInfo,
    setIsLogin,
  };
});
